import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// 导入 Element Plus 暗黑模式 CSS 变量
import 'element-plus/theme-chalk/dark/css-vars.css'
// 导入自定义暗色主题增强配置
import './assets/element-dark.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import App from './App.vue'
import router from './router'
import { registerMicroApps, start } from 'qiankun'
import { nextTick } from 'vue'
import { microAppStyleManager } from './utils/cssSandbox'
import { microThemeBridge } from './utils/microThemeBridge'
import { themeDSL } from './utils/themeDSL'
import { setupDirectives } from './utils/directives'
import TokenManager from './utils/tokenManager'
import { microApps, initMicroAppEntries } from './microApps.config'
import { initTitleObserver } from './utils/titleObserver'

import './assets/main.css'

// 主题DSL系统已在导入时自动初始化，无需重复初始化

// 创建Vue应用实例
const app = createApp(App)

// 注册插件
app.use(createPinia())
app.use(router)
app.use(ElementPlus, {
  locale: zhCn,
})

// 注册自定义指令
setupDirectives(app)

// 初始化标题观察器
initTitleObserver()


// 初始化token刷新服务
if (TokenManager.isAuthenticated()) {
  TokenManager.getInstance().init()
}

// 暴露 TokenManager 到全局，供灰度查询使用
if (typeof window !== 'undefined') {
  (window as any).__TOKEN_MANAGER__ = TokenManager;
}

// 挂载应用
app.mount('#app')

// 初始化微应用入口地址（支持灰度版本）
// 需要在注册微应用之前完成
initMicroAppEntries().then(() => {
  // 注册微应用
  registerMicroApps(
  microApps.map(app => ({
    name: app.name,
    entry: app.entry,
    container: app.name === 'react-devops' ? '#subapp-viewport' : '#subapp-container',
    activeRule: app.activeRule
  })), {
  beforeLoad: [
    app => {
      return Promise.resolve()
    }
  ],
  beforeMount: [
    app => {
      // 注册微应用样式隔离
      const containerSelector = app.name === 'react-devops' ? '#subapp-viewport' : '#subapp-container'
      const container = document.querySelector(containerSelector) as HTMLElement
      if (container) {
        microAppStyleManager.registerApp(app.name, container)
        // 主题桥注册容器并立即同步
        microThemeBridge.register(app.name, container)
      }
      return Promise.resolve()
    }
  ],
  afterMount: [
    app => {
      return Promise.resolve()
    }
  ],
  afterUnmount: [
    app => {
      // 卸载微应用样式隔离
      microAppStyleManager.unregisterApp(app.name)
      return Promise.resolve()
    }
  ]
  })
  
  // 等待 DOM 挂载完成后再启动 qiankun
  nextTick(() => {
    start({
      prefetch: 'all', // 预加载所有微应用
      sandbox: {
        strictStyleIsolation: false, // 关闭严格的样式隔离（会创建Shadow DOM）
        experimentalStyleIsolation: true, // 开启实验性的样式隔离，提供样式隔离但不阻止外部样式
      }
    })
    // 启动主题桥监听，统一驱动所有微应用的主题变量
    microThemeBridge.start()
  })
}).catch((error) => {
  // 初始化失败，使用默认配置
  console.error('[初始化微应用入口地址失败]', error);
  // 仍然注册微应用，使用默认的 CDN 地址
  registerMicroApps(
    microApps.map(app => ({
      name: app.name,
      entry: app.entry || `https://mybox-1257251314.cos.ap-chengdu.myqcloud.com/www/micro/${app.name}/index.html`,
      container: app.name === 'react-devops' ? '#subapp-viewport' : '#subapp-container',
      activeRule: app.activeRule
    })), {
    beforeLoad: [
      app => {
        return Promise.resolve()
      }
    ],
    beforeMount: [
      app => {
        const containerSelector = app.name === 'react-devops' ? '#subapp-viewport' : '#subapp-container'
        const container = document.querySelector(containerSelector) as HTMLElement
        if (container) {
          microAppStyleManager.registerApp(app.name, container)
          microThemeBridge.register(app.name, container)
        }
        return Promise.resolve()
      }
    ],
    afterMount: [
      app => {
        return Promise.resolve()
      }
    ],
    afterUnmount: [
      app => {
        microAppStyleManager.unregisterApp(app.name)
        return Promise.resolve()
      }
    ]
  })
  
  nextTick(() => {
    start({
      prefetch: 'all',
      sandbox: {
        strictStyleIsolation: false,
        experimentalStyleIsolation: true,
      }
    })
    microThemeBridge.start()
  })
})